#!/bin/bash
#
# Project Kimchi
#
# Copyright IBM Corp, 2013-2016
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

HAVE_UNITTEST=@HAVE_PYMOD_UNITTEST@
PYTHON_VER=@PYTHON_VERSION@

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

if [ "$1" = "-v" ]; then
    OPTS="-v"
    shift
else
    OPTS=""
fi

if [ $# -ne 0 ]; then
    ARGS="$@"
else
    ARGS=`find -name "test_*.py" | xargs -I @ basename @ .py`
fi

CMD="python3 -m unittest"

NUM_TESTS=0
TIME=0
declare -A FAILED_UT    # dict to store failed unit tests and its OUTPUT_FILE
OUTPUT_FILE=$(mktemp)
for UT in $ARGS; do
    echo -n "***** Running unit test: $UT... "
    # ../../../../../ refers to the project root
    # ../../../../ refers to wok directory
    # ../../../ refers to plugins directory
    OUTPUT=$(PYTHONPATH=../../../../../:../../../../:../../../ \
    PYTHONWARNINGS="ignore:Unverified HTTPS request" \
    $CMD $OPTS $UT 2>&1)
    RES=$?
    if [ $RES -ne 0 ]; then
        # unit test has failed, so keep the OUTPUT_FILE and print the results
        STATS=$(echo "$OUTPUT" | grep "Ran")
        echo -e "\t ${RED}FAILED${NC} - $STATS"
        ERROR_LOG_BEGIN=$(echo "$OUTPUT" | grep -n "^\==*" | head -n1 | cut -d":" -f1)
        ERROR_LOG_END=$(echo "$OUTPUT" | wc -l)
        echo "$OUTPUT" | tail -n $((${ERROR_LOG_END}-${ERROR_LOG_BEGIN}+1))
        FAILED_UT+=([$UT]=$(echo "$OUTPUT" | grep FAILED | cut -d" " -f2-4))
        echo "$OUTPUT" >> $OUTPUT_FILE
    else
        # unit test has passed, so print the results and delete the OUTPUT_FILE
        STATS=$(echo "$OUTPUT" | grep "Ran")
        echo -e "\t ${GREEN}PASSED${NC} - $STATS"
    fi
    TES=$(echo $STATS | cut -d" " -f2)
    NUM_TESTS=$(echo "$NUM_TESTS + $TES" | bc)
    TES=$(echo $STATS | cut -d" " -f5)
    TIME=$(echo "$TIME + ${TES:0:-1}" | bc)
done

# Print summary results
echo -e "======================================================================"
echo -e "===================== Kimchi Unit Tests Summary ======================"
echo -e "Ran $NUM_TESTS tests in $TIME seconds."
for i in "${!FAILED_UT[@]}"; do
    echo -e "$i FAILED: ${FAILED_UT[$i]} - full log available at $OUTPUT_FILE"
done
